package com.youle.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by
 *
 * @author touni
 * @date 2019/4/22
 * @time 11:48
 */
@Service
public class UploadService {




    @Autowired
    private FastFileStorageClient storageClient;



    @Value("${imagedomainname}")
    private String imageDomainName;

    /**
     * 处理图片的上传 并返回图片的URL
     * @param
     * @return
     */
    public ResponseEntity<String> uploadFile(MultipartFile file) {

        //上传文件
        StorePath storePath = null;
        try {
            storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), StringUtils.substringAfterLast(file.getOriginalFilename(),"."), null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //拼接URL并返回
        String storePathFullPath = storePath.getFullPath();
        if (StringUtils.isEmpty(storePathFullPath)) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败，请稍后重试");}
        System.out.println(storePathFullPath);
        return ResponseEntity.status(HttpStatus.ACCEPTED).body(imageDomainName+storePathFullPath);
    }
}
